package com.ita.acmsystem.merchant.servlet;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.ita.acmsystem.merchant.entity.Foods;
import com.ita.acmsystem.merchant.service.IFoodService;
import com.ita.acmsystem.merchant.service.impl.FoodServiceImpl;
import com.ita.acmsystem.merchant.validator.impl.FoodsNameValidatorImpl;
import com.ita.acmsystem.merchant.validator.impl.FoodsPriceValidatorImpl;

/**
 * Servlet implementation class UpdateServlet
 */
public class UpdateFoodsServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private IFoodService foodService = new FoodServiceImpl();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UpdateFoodsServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		updateFood(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		updateFood(request, response);
	}

	@SuppressWarnings("unused")
	private void updateFood(HttpServletRequest request,
			HttpServletResponse response) {
		String foodId = null, foodName = null, foodPrice = null, foodFoodType = null, foodPic = null, newFoodPic = null, merchantId = null;
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (isMultipart) {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);

			List<FileItem> items = null;
			try {
				items = upload.parseRequest(request);
				Iterator<FileItem> itor = items.iterator();
				while (itor.hasNext()) {
					FileItem item = itor.next();
					if (item.isFormField()) {
						System.out.println(item.getFieldName() + ":"
								+ item.getString());
						switch (item.getFieldName()) {
						case "foodId":
							foodId = item.getString();
							break;
						case "foodName":
							foodName = item.getString("UTF-8");
							break;
						case "foodPrice":
							foodPrice = item.getString();
							break;
						case "foodFoodType":
							foodFoodType = item.getString();
							break;
						case "foodPic":
							foodPic = item.getString();
							break;
						case "merchantId":
							merchantId = item.getString();
							break;
						default:
							break;
						}
					} else {
						// TODO
						// upload image
						long size = item.getSize();
						if (size != 0) {
							System.out.println("file size:" + item.getSize());
							System.out.println("file name:"
									+ item.getFieldName());
							System.out.println("file type:"
									+ item.getContentType());
							String fileName = UUID.randomUUID() + ".jpg";
							File file = new File(request.getSession()
									.getServletContext().getRealPath("/")
									+ "foodpic\\" + fileName);
							// System.out.println(file.getAbsolutePath());
							// newFoodPic = "http://localhost:8880/foodpic/" +
							// fileName;

							// read host and port from property.propertties
							InputStream is = UpdateFoodsServlet.class
									.getClassLoader().getResourceAsStream(
											"property.propertties");
							Properties prop = new Properties();
							prop.load(is);
							String host = prop.getProperty("host");
							String port = prop.getProperty("port");

							newFoodPic = "http://" + host + ":" + port
									+ "/foodpic/" + fileName;
							item.write(file);
						}
					}
				}
				if (newFoodPic != null)
					foodPic = newFoodPic;

				StringBuffer sb = new StringBuffer();
				sb.append(new FoodsNameValidatorImpl().validate(foodName));
				sb.append(new FoodsPriceValidatorImpl().validate(foodPrice));
				String message = sb.toString();
				if (!"".equals(message)) {
					// request.setAttribute("foodId", foodId);
					// request.setAttribute("message", message);
					System.out.println("UpdateFoodsServlet" + message);
					request.getRequestDispatcher(
							"UpdateFoodsContentServlet?foodId=" + foodId
									+ "&message=" + message).forward(request,
							response);
				} else {
					System.out.println("foodPic:" + foodPic);
					Foods food = new Foods(foodId, foodName, foodPrice,
							foodPic, foodFoodType, merchantId);
					PrintWriter writer = response.getWriter();
					if (foodService.updateFoods(food) == true) {
						response.sendRedirect("ContentServlet");
					} else {
						writer.write("<h1>Sorry! Update Fail!</h1>");
					}
					writer.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
